<?php
require 'auth.php';
require '../config/config.php';

if(!isset($_POST['submit'])){
	header("Location: ../news.php");
	exit();
}
mydb_connect();

$title= $_POST['title'];
$description= $_POST['description'];
$video = $_POST['video'];
$category= $_POST['category'];
$section = $_POST['section'];
$content = $_POST['content'];
if($description == " " || $title == " " || $content == " " || $category== "" || $section== ""){
	die("Error: Empty fields aren't accepted. <a href='../news.php'><< Go back</a>");
}
if(isset($_POST['isSelf']) && $_POST['isSelf']=="yes"){
	$author_id = $_SESSION['USER_ID'];
	$physical_author_id = $_SESSION['USER_ID'];
}
else{
	if($_POST['other-author-id']== ""){
		echo "Author not selected. <a href='../news.php'><< Go back</a>";
		exit();
	}
	$author_id = $_POST['other-author-id'];
	$physical_author_id = $_SESSION['USER_ID'];
}


$path = "../images/";

	$valid_formats = array("jpg", "png", "gif", "bmp","JPG","PNG","GIF","BMP","jpeg","JPEG");
	//if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
		//{
			$name = $_FILES['img_name']['name'];
			$size = $_FILES['img_name']['size'];
			$r=10;
			if(strlen($name))
				{
					$r =1;
					list($txt, $ext) = explode(".", $name);
					$ext = pathinfo($name, PATHINFO_EXTENSION);
					if(in_array($ext,$valid_formats))
					{
						$r =2;
					if($size<(1024*1024))
						{
							$r =3;
							
							$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
							$tmp = $_FILES['img_name']['tmp_name'];
								
									$r =4;
								//mysql_query("INSERT INTO users image value('$actual_image_name') ");
								$insert=$conn->prepare("INSERT INTO `news`(`id`,`title`,`pub_date`,`img_name`,`ispub`,`author_id`,`physical_author_id`,`category_id`,`content`,`description`,`section`,`video`) VALUES(NULL,:title,NOW(), :actual_image_name, :ispub, :author_id ,:physical_author_id,:category, :content,:description,:section, :video)");	
									//echo "<img src='uploads/".$actual_image_name."'  class='preview'>";
								$insert->execute(array('title' => $title, 'actual_image_name'=>$actual_image_name, 'ispub'=> 'no', 'author_id'=>$author_id ,'physical_author_id'=>$physical_author_id,'category'=>$category,'content'=> $content,'description'=> $description,'section'=> $section, 'video'=>$video));
								if(!$insert){
									echo $insert->errorInfo();
									exit();
								}
							if($insert){
								move_uploaded_file($tmp, $path.$actual_image_name);
								header("location:../news.php?publish=success");
								exit();	
							}
							else{
								header("location:../news.php?publish=fail");
								exit();
							}
						}
						else
						{echo "Image file size max 1 MB";$r=88;}					
						}
						else
						{echo "Invalid file format..";$r=99;}	
				}else {
				echo "NO IMAGE";
			}
			?>